<?php 
class Application_Model_Product extends Application_Model_DomainObject{
	
	protected $_id;
	
    /**
     * 商品在其所在网站上的ID，与后面的SKUS无关
     * @var type 
     */
	protected $_sku;
	
	protected $_name;

	protected $_price;
	
	protected $_image;
	
	protected $_remoteImage;
	
	protected $_url;
	
	protected $_weight;
	
	protected $_shopId;
	
	protected $_description;
	
	protected $_shipFee;

    protected $_skus;
    
    protected $_propertyAlias;
    
    protected $_hasSkus;
    
    protected $_propertyImages;
    
    protected $_quantity;
    
    protected $_promotionError;

    const DEFAULT_IMAGE='/images/null.gif';


    /**
	 * 根据SKU返回一个产品
	 * @param string $sku
	 * @return Application_Model_Product
	 */
	public static function getBySku($sku){
		return self::getDao()->queryOne(array('sku'=>$sku));
	}
    
    public static function getByUrl($url){
        return self::getDao()->queryOne(array('url'=>$url));
    }

    
    /**
     * 获取商品对应的SKU
     * @return type 
     */
    public function getSkus(){
        if($this->_skus==NULL){
            if(isset($this->_id))
                $this->_skus = Application_Model_Sku::getByProductId($this->Id);
            else
                $this->_skus = array();
        }
        return $this->_skus;
    }
        
     /**
     * 添加一个SKU
     * @param Application_Model_Sku $sku 
     */
    public function addSku($sku){
        $this->getSkus();
        $sku->ProductId = $this->Id;
        array_unshift($this->_skus, $sku);
    }
    
    public function save() {
        parent::save();
        foreach ($this->getSkus() as $sku) {
            $sku->ProductId = $this->Id;
            $sku->save();
        }
    }
	
    /**
     * 返回商品的可选项
     * @return array 
     */
    public function getOption(){
        if (!$this->HasSkus)
            return array();
        
        //属性别名映射 
        $aliaMap = array();
        $alias = explode(';', $this->_propertyAlias);
        foreach ($alias as $alia) {
            $names = explode(':', $alia);
            if(count($names) <=2)
                continue;
            $aliaMap[$names[0].':'.$names[1]]=$names[2];
        }
        
        //属性图片映射
        $imageMap = array();
        $images = explode(';', $this->_propertyImages);
        foreach ($images as $image){
            if ($image == NULL || $image == '')
                continue;;
            $split = explode('##', $image);
            $imageMap[$split[0]] = $split[1];
        }
        
        $option = array();
        //遍历所有的SKU
        
        foreach ($this->getSkus() as $sku) {
//            echo $sku->Id."<br>";
            $props = explode(';', $sku->Properties);
            
            //遍历所有的属性值
            foreach ($props as $prop) {
                $names = explode(':', $prop);
                
                //根据属性名获取属性值表,如果此名字没有添加,则新添加一个
                $values=NULL;
                if (isset($option[$names[2]])){
                    $values = $option[$names[2]];
                }
                else{
                    $values = array();
                    $option[$names[2]]=$values;
                }
                
                $id = $names[0].':'.$names[1];
                
                //如果此属性值还没有添加,则添加一个
                if (!isset($values[$id])){
                    $value = array();
                    $name = $names[3];
                    //获取属性值，如果有别名，就用别名替代。
                    if (isset($aliaMap[$id])){
                        $name = $aliaMap[$id];
                    }
                    $value['id'] = $id;
                    $value['name'] = $name;
                    if (isset($imageMap[$id])){
                        $value['image'] = $imageMap[$id];
                    }
                    $values[$id] = $value;
                    
                }
                
                $option[$names[2]] = $values;
                
                        
            }
        }
        return $option;
    }
    
    private $_shop;
    public function getShop(){
        if($this->_shop == NULL)
            $this->_shop = Application_Model_Shop::load($this->ShopId);
        return $this->_shop;
    }
	
	public static function parsePropertyAlias($str){
		if (preg_match('{^[a-z]:\d+}', $str)) {
			$o = unserialize($str) ?: array();
			$sp = '';
			$propertyAlias = '';
			$keys = array_keys($o);
			$values = array_values($o);
			foreach ($keys as $key => $value) {
				$propertyAlias .= $sp . $value . ':' . $values[$key];
				if ($sp == '') $sp = '|';
			}
			return $propertyAlias;
		} else {
			return $str;	
		}
	}
}